package com.lechuang.ssgou.view.activity.home;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.jude.rollviewpager.OnItemClickListener;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.hintview.ColorPointHintView;
import com.lechuang.ssgou.R;
import com.lechuang.ssgou.base.BaseFragment;
import com.lechuang.ssgou.model.bean.HomeBannerBean;
import com.lechuang.ssgou.model.bean.HomeGunDongTextBean;
import com.lechuang.ssgou.model.bean.HomeKindBean;
import com.lechuang.ssgou.model.bean.HomeLastProgramBean;
import com.lechuang.ssgou.model.bean.HomeProgramBean;
import com.lechuang.ssgou.model.bean.HomeSearchResultBean;
import com.lechuang.ssgou.presenter.CommonAdapter;
import com.lechuang.ssgou.presenter.adapter.BannerAdapter;
import com.lechuang.ssgou.presenter.adapter.HomeRecyclerAdapter;
import com.lechuang.ssgou.presenter.adapter.MyHomeAdapter;
import com.lechuang.ssgou.presenter.net.Netword;
import com.lechuang.ssgou.presenter.net.ResultBack;
import com.lechuang.ssgou.presenter.net.netApi.HomeApi;
import com.lechuang.ssgou.utils.Utils;
import com.lechuang.ssgou.view.activity.live.LiveActivity;
import com.lechuang.ssgou.view.activity.ui.LoginActivity;
import com.lechuang.ssgou.view.defineView.AutoTextView;
import com.lechuang.ssgou.view.defineView.MGridView;
import com.lechuang.ssgou.view.defineView.ViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import se.emilsjolander.stickylistheaders.StickyListHeadersListView;

/**
 * 作者：li on 2017/11/12 09:46
 * 邮箱：961567115@qq.com
 * 修改备注:
 */
public class HomeFragment2 extends BaseFragment {

    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.tv_sign)
    TextView tvSign;
    @BindView(R.id.iv_tryAgain)
    ImageView ivTryAgain;
    @BindView(R.id.ll_noNet)
    LinearLayout llNoNet;
    @BindView(R.id.slh)
    StickyListHeadersListView slh;
   /* @BindView(R.id.refreshScrollView)
    PullToRefreshScrollView refreshScrollView;*/
    @BindView(R.id.iv_top)
    ImageView ivTop;

    MGridView gvKind;

    RollPagerView rvBanner;
    AutoTextView tvAutoText;


    ImageView ivProgram1;

    ImageView ivProgram2;

    ImageView ivProgram3;

    ImageView ivProgram4;
    View ivJump;
    ImageView lastRollViewPager;

    TabLayout tlTab;

    ImageView ivItem;

    Unbinder unbinder;

    private View v;
    private ScrollView scrollView;
    //最下栏目广告图
    private MyHomeAdapter myHomeAdapter;
    //private RecyclerView rvHome;

    SharedPreferences sp;
    private ArrayList<String> text = null; //首页滚动文字
    //分页
    private int page = 1;
    HashMap<String, String> map = new HashMap<>();
    //tablayoute标题
    private List<HomeKindBean.ListBean> topTabList = new ArrayList<>();
    private int rootId = -1;
    private int position = 0;

    private List<HomeSearchResultBean.ProductListBean> productList = new ArrayList<>();

    private List<HomeGunDongTextBean.IndexMsgListBean> textlist;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.fragment_home1, container, false);
        unbinder = ButterKnife.bind(this, v);
        initView();
        getData();
        sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
        return v;
    }

    private void getData() {
        getHomeBannerData();
        getHomeKindData();
        getHomeScrollTextView();
        getHomeProgram();
        getLastImage();
        getLastProgramData();
    }

    private void initView() {
     /*   refreshScrollView = (PullToRefreshScrollView) v.findViewById(R.id.refreshScrollView);
        scrollView = refreshScrollView.getRefreshableView();  //refreshScrollView最上方显示,防止refreshScrollView初始化时不在最上方
        //获取焦点  必须先获取焦点才能在顶部  另外内部的listview gridView不能有焦点
        refreshScrollView.setFocusable(true);
        refreshScrollView.setFocusableInTouchMode(true);
        refreshScrollView.requestFocus();
        refreshScrollView.getRefreshableView().scrollTo(0, 0);*/
        myHomeAdapter = new MyHomeAdapter(getActivity());
        slh.setAdapter(myHomeAdapter);
        //轮播图

    }

    private List<HomeBannerBean.IndexBannerList> bannerList;

    //获取首页轮播图数据
    private void getHomeBannerData() {
        //首页轮播图数据
        Netword.getInstance().getApi(HomeApi.class)
                .homeBanner()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultBack<HomeBannerBean>(getActivity()) {

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        hideWaitDialog();
                    }

                    @Override
                    public void successed(HomeBannerBean result) {
                        if (result == null) {
                            return;
                        }
                        bannerList = result.indexBannerList0;
                        myHomeAdapter.setBannerList(bannerList);
                        /*rvBanner.setOnItemClickListener(new OnItemClickListener() {
                            @Override
                            public void onItemClick(int position) {
                                //获取到点击条目
                                int programaId = bannerList.get(position).programaId;
                                if (programaId == 1) {
                                    //栏目1
                                    startActivity(new Intent(getActivity(), ProgramDetailActivity.class)
                                            .putExtra("programaId", 1));
                                } else if (programaId == 2) {
                                    //栏目2
                                    startActivity(new Intent(getActivity(), ProgramDetailActivity.class)
                                            .putExtra("programaId", 2));
                                } else if (programaId == 3) {
                                    //栏目3
                                    startActivity(new Intent(getActivity(), ProgramDetailActivity.class)
                                            .putExtra("programaId", 3));
                                } else if (programaId == 4) {
                                    //栏目4
                                    startActivity(new Intent(getActivity(), ProgramDetailActivity.class)
                                            .putExtra("programaId", 4));
                                } else if (programaId == 5) {
                                    //栏目5
                                    handler.sendEmptyMessage(1);
                                } else {
                                    // TODO: 2017/10/1 跳转奔溃
                                    startActivity(new Intent(getActivity(), EmptyWebActivity.class)
                                            .putExtra("url", bannerList.get(position).link));
                                }
                            }
                        });*/

                    }
                });
    }

    //获取首页分类数据
    private void getHomeKindData() {

      /*  gvKind.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        startActivity(new Intent(getActivity(), KindDetailActivity.class)
                                .putExtra("type", 1).putExtra("name", "官方推荐"));
                        break;
                    case 1:
                        startActivity(new Intent(getActivity(), KindDetailActivity.class)
                                .putExtra("type", 2).putExtra("name", "9.9包邮"));
                        break;
                    case 2:
                        startActivity(new Intent(getActivity(), KindDetailActivity.class)
                                .putExtra("type", 3).putExtra("name", "1元试用"));
                        break;
                    case 3:
                        startActivity(new Intent(getActivity(), KindDetailActivity.class)
                                .putExtra("type", 4).putExtra("name", "品牌优选"));
                        break;
                    case 4:
                        startActivity(new Intent(getActivity(), LiveActivity.class));


                        break;
                }
            }
        });*/


    }

    //首页滚动文字数据
    private void getHomeScrollTextView() {
        Netword.getInstance().getApi(HomeApi.class)
                .gunDongText()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultBack<HomeGunDongTextBean>(getActivity()) {
                               @Override
                               public void successed(HomeGunDongTextBean result) {
                                   if (result == null) {
                                       return;
                                   }
                                   textlist = result.indexMsgList;
                                   myHomeAdapter.setTextlist(textlist);
                               }
                           }
                );

    }

    //首页4个图片栏目数据
    private void getHomeProgram() {
        Netword.getInstance().getApi(HomeApi.class)
                .homeProgramaImg()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultBack<HomeProgramBean>(getActivity()) {
                    @Override
                    public void successed(HomeProgramBean result) {
                        if (result == null) {
                            return;
                        }
                        List<HomeProgramBean.ListBean> list = result.programaImgList;

                        myHomeAdapter.setListProgrm(list);
                        /*ivProgram1.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startActivity(new Intent(getActivity(), ProgramDetailActivity.class)
                                        .putExtra("programaId", list.get(0).programaId));
                            }
                        });
                        ivProgram2.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startActivity(new Intent(getActivity(), ProgramDetailActivity.class)
                                        .putExtra("programaId", list.get(1).programaId));
                            }
                        });
                        ivProgram3.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startActivity(new Intent(getActivity(), ProgramDetailActivity.class)
                                        .putExtra("programaId", list.get(2).programaId));
                            }
                        });
                        ivProgram4.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startActivity(new Intent(getActivity(), ProgramDetailActivity.class)
                                        .putExtra("programaId", list.get(3).programaId));
                            }
                        });*/
                    }
                });

    }

    //获取最底部图片
    private void getLastImage() {
        //底部图片
        Netword.getInstance().getApi(HomeApi.class)
                .homeLastPage(page)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultBack<HomeLastProgramBean>(getActivity()) {
                    @Override
                    public void successed(HomeLastProgramBean result) {
                        if (result == null)
                            return;
                        List<HomeLastProgramBean.programaBean.ListBean> list1 = result.programa.indexBannerList;

                        myHomeAdapter.setLastImage(list1);
                    }

                });
        myHomeAdapter.notifyDataSetChanged();
    }

    //首页最下栏目的数据
    private void getLastProgramData() {

        Netword.getInstance().getApi(HomeApi.class)
                .homeClassify()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultBack<HomeKindBean>(getActivity()) {
                    @Override
                    public void successed(HomeKindBean result) {
                        if (result == null) {
                            return;
                        }
                        List<HomeKindBean.ListBean> list = result.tbclassTypeList;
                        myHomeAdapter.setHead2list(list);
//                        initFragment();
                        initTabView();
                        //initGride();
                        myHomeAdapter.notifyDataSetChanged();
                    }
                });

    }

    /**
     * 初始化tablayout
     */
    private void initTabView() {
        initRecyclerData();
        /*tlTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //记录当前位置
                position = (int) tab.getTag();
                rootId = topTabList.get(HomeFragment2.this.position).rootId;
                page = 1;
                initRecyclerData();
                //ToastManager.getInstance().showShortToast("onTabSelected" + postion);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });*/
    }

    /**
     * 初始化底部数据
     */
    private void initRecyclerData() {
        showWaitDialog("");
        map.clear();
        map.put("page", page + "");
        if (rootId != -1) {  //Integer classTypeId   分类id,精选不传
            map.put("classTypeId", rootId + "");
        } else {
            if (map.containsKey("classTypeId")) {
                map.remove("classTypeId");
            }
            //Integer is_official   精选传1,其他不传
            map.put("is_official", 1 + "");
        }
        Netword.getInstance().getApi(HomeApi.class)
                .searchResult(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultBack<HomeSearchResultBean>(getActivity()) {
                    @Override
                    public void successed(HomeSearchResultBean result) {
                        if (result == null)
                            return;
                        List<HomeSearchResultBean.ProductListBean> list = result.productList;
                     /*   refreshScrollView.setMode(list.size() > 0 ? PullToRefreshBase.Mode.BOTH : PullToRefreshBase.Mode.PULL_FROM_START);*/
                        if (page == 1) {
                            productList.clear();
                        }
                        productList.addAll(list);
                        if (page > 1 && list.isEmpty()) {
                            Utils.show(getActivity(), "亲,已经到底了~");
                            return;
                        }
                        myHomeAdapter.setListProduct(productList);

                       /*  int isAgencyStatus = sp.getInt("isAgencyStatus", 0);

                       if (mAdapter == null) {
                            mAdapter = new HomeRecyclerAdapter(productList, getContext(), isAgencyStatus);
                           // rvHome.setLayoutManager(new LinearLayoutManager(getContext()));
                            //rvHome.setAdapter(mAdapter);
                            mAdapter.setOnItemClickLitener(new HomeRecyclerAdapter.OnItemClickLitener() {
                                @Override
                                public void onItemClick(View view, int position) {
                                    startActivity(new Intent(getActivity(), ProductDetailsActivity.class)
                                            .putExtra("alipayCouponId", productList.get(position).alipayCouponId)
                                            .putExtra("alipayItemId", productList.get(position).alipayItemId)
                                            .putExtra("name", productList.get(position).name)
                                            .putExtra("price", productList.get(position).price + "")
                                            .putExtra("preferentialPrice", productList.get(position).preferentialPrice)
                                            .putExtra("shareIntegral", productList.get(position).shareIntegral)
                                            .putExtra("shopType", productList.get(position).shopType)
                                            .putExtra("img", productList.get(position).imgs));
                                }
                            });
                           // rvHome.setNestedScrollingEnabled(false);
                        } else {
                            mAdapter.notifyDataSetChanged();
                        }*/

                        hideWaitDialog();

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        hideWaitDialog();
                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.tv_search, R.id.tv_sign, R.id.iv_tryAgain, R.id.iv_top})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_search:
                break;
            case R.id.tv_sign:
                break;
            case R.id.iv_tryAgain:
                break;
            case R.id.iv_top:
                break;
        }
    }

    //置顶
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            int high = v.findViewById(R.id.iv_jump).getTop();
                          /*  refreshScrollView.getRefreshableView().smoothScrollTo(0, high);*/
                        }
                    }).start();
                    break;
                default:
                    break;
            }

        }
    };

    //刷新加载
    private PullToRefreshBase.OnRefreshListener2 refresh = new PullToRefreshBase.OnRefreshListener2() {

        @Override
        public void onPullDownToRefresh(PullToRefreshBase refreshView) {

            // 显示最后更新的时间
            //refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
            page = 1;

            getData();
          /*  refreshScrollView.onRefreshComplete();*/
        }

        @Override
        public void onPullUpToRefresh(PullToRefreshBase refreshView) {
            // 显示最后更新的时间
            //refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
            showWaitDialog("");
            page += 1;
            getLastProgramData();
         /*   refreshScrollView.onRefreshComplete();*/
        }
    };

}
